package cn.edu.ctbu.lab.service.impl;

import cn.edu.ctbu.lab.dao.StudentRepository;
import cn.edu.ctbu.lab.domain.Student;
import cn.edu.ctbu.lab.exception.REnum;
import cn.edu.ctbu.lab.exception.RException;
import cn.edu.ctbu.lab.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.List;
import java.util.Optional;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentRepository studentRepository;


    public Optional<Student> findById(Integer id){

        Optional<Student> student=studentRepository.findById(id);
        return student;
    }


    public List<Student> findAll(){

        List<Student> myList=studentRepository.findAll();
        return myList;
    }

    public Page<Student> findByPage(int pageIndex, int pageSize){

        Sort sort =  Sort.by(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(pageIndex, pageSize, sort);
        Page<Student> myList=studentRepository.findAll(pageable);

        return myList;

    }




    public Student add(Student student){
        studentRepository.save(student);
        return student;
    }

    public Student update(Student student){
        Student studentOld=studentRepository.getOne(student.getId());
        //todo sth....
        studentRepository.save(student);
        return student;
    }


    public int delete(Student student){

        try{

            studentRepository.delete(student);
        }catch (Exception e){

            //throw  e;
            return -1;
        }
        return 1;
    }

    public  int delete(Integer id){
        Student student=studentRepository.getOne(id);

        return delete(student);

    }


    /**
     * 按学生的登录名和密码取学生，如果取到，那么返回此学生;如果取不到，扔出异常
     * @param name
     * @param password
     * @return
     */
    public Student validUserNameAndPassword(String name,String password) throws  Exception{

        List<Student> students=studentRepository.findByNoAndPassword(name,password);
        if(students.size()==0){
            throw new RException(REnum.LOGIN_ERR);

        }

        return students.get(0);
    }
}
